﻿using System.Linq;
using AutoMapper;
using Tools.Common.UnitOfWork.Contracts;
using Web.App.Infrastructure.NHibernate.Fetching;
using Web.App.Infrastructure.NHibernate.Repository;
using Webshop20.Domain.Catalog.Core;
using Webshop20.Domain.Customers.Services.Contracts;

namespace Webshop20.Domain.Catalog.Repositories.Contracts
{

    public class VisitorRepository : NHRepository<Visitor>
    {
        private ICustomerInformationService customerInformationService; 

        public VisitorRepository(IFetchingStrategyFactory fetchingStrategyFactory, IUoWContainer unitOfWorkContainer, ICustomerInformationService customerInformationService) : base(fetchingStrategyFactory, unitOfWorkContainer)
        {
            this.customerInformationService = customerInformationService;
        }

        public override Visitor FindById(object id)
        {
            var visitor = base.FindById(id);
            var customerInfo = customerInformationService.GetCustomerById((int)id);
            return Mapper.Map(customerInfo, visitor);
        }

        public override IQueryable<Visitor> FindBySpecification(Tools.Domain.Specifications.ISpecification<Visitor> specification)
        {
            var visitors = base.FindBySpecification(specification);
            var customers = customerInformationService
                                .GetCustomersById(visitors.Select(visitor=>visitor.Id));

            foreach (var visitor in visitors)
            {
                var customer = customers.Where(cust => cust.Id == visitor.Id).FirstOrDefault();
                visitor.FirstName = customer.FirstName;
                visitor.LastName = customer.LastName;
                visitor.EMail = customer.EMail;
            }

            return visitors;
        }


    }
}
